package fw_event

import (
	"context"
	"github.com/golang-module/carbon/v2"
	"github.com/samber/lo"
	"time"
	"transport/framework/fw_db/fw_db_self"
	"transport/framework/fw_db/fw_db_wms"
	"transport/framework/fw_log"
	"transport/web/web_mapper"
	"transport/web/web_model"
	"transport/web/web_vo"
	"transport/web/web_wms_mapper"
)

type EventChanCmd int

const (
	EVENT_CMD_SYNC_PRODUCT_INFO   EventChanCmd = 0x01
	EVENT_CMD_SYNC_ROUTE_INFO     EventChanCmd = 0x02
	EVENT_CMD_SYNC_MERCHANTS_INFO EventChanCmd = 0x03
	EVENT_CMD_SYNC_ORDER_INFO     EventChanCmd = 0x04
	EVENT_CMD_SYNC_TRUSTEE_INFO   EventChanCmd = 0x05
)

type EventStateMsg struct {
	Cmd   EventChanCmd
	Value interface{}
	Ext1  interface{}
	Ext2  interface{}
}

var EventStateChan = make(chan EventStateMsg, 1000)

func EventChanDelivery(cmd EventChanCmd, value interface{}, ext1 interface{}, ext2 interface{}) {
	msgChan := EventStateMsg{
		Cmd:   cmd,
		Value: value,
		Ext1:  ext1,
		Ext2:  ext2,
	}
	EventStateChan <- msgChan
}
func EventPro() {
	go func() {
		timer := time.NewTicker(time.Second * 1)
		for {
			select {
			case <-timer.C:
			case msg := <-EventStateChan:
				switch {
				// 商品信息同步
				case msg.Cmd == EVENT_CMD_SYNC_PRODUCT_INFO:
					//mapperProductInfoWms := web_wms_mapper.ProductInfoMapper{
					//	DB:  fw_db_wms.GetSqlserverDB(),
					//	Ctx: context.Background(),
					//}
					//mapperProductInfoTrans := web_mapper.ProductInfoMapper{
					//	DB:  fw_db_wms.GetSqlserverDB(),
					//	Ctx: context.Background(),
					//}
					//items, _, err := mapperProductInfoWms.List()
					//fw_log.Slogger.Info(lo.IsNil(items))
					//if err != nil {
					//	break
					//}
					//for _, v := range items {
					//	fw_log.Slogger.Info(v)
					//}
					break
					//线路信息同步
				case msg.Cmd == EVENT_CMD_SYNC_ROUTE_INFO:
					mapperCustomerInfoWms := web_wms_mapper.CustomerMapper{
						DB:  fw_db_wms.GetSqlserverDB(),
						Ctx: context.Background(),
					}
					mapperRoute := web_mapper.RouteMapper{
						DB:   fw_db_self.GetSqliteDB(),
						Ctx:  context.Background(),
						Lock: fw_db_self.GetSqliteLock(),
					}
					routeLabels, err := mapperCustomerInfoWms.QueryRouteLabelList()
					if err != nil {
						fw_log.Slogger.Info(err.Error())
						break
					}
					for _, v := range routeLabels {
						var modelRoute web_model.TransRoute
						modelRoute.Name = v
						_, err = mapperRoute.Upsert(&modelRoute)
						if err != nil {
							fw_log.Slogger.Info(err.Error())
						}
					}
					break
					//客商同步
				case msg.Cmd == EVENT_CMD_SYNC_MERCHANTS_INFO:
					mapperCustomerInfoWms := web_wms_mapper.CustomerMapper{
						DB:  fw_db_wms.GetSqlserverDB(),
						Ctx: context.Background(),
					}
					mapperRoute := web_mapper.RouteMapper{
						DB:   fw_db_self.GetSqliteDB(),
						Ctx:  context.Background(),
						Lock: fw_db_self.GetSqliteLock(),
					}
					mapperTrutee := web_mapper.TrusteeMapper{
						DB:   fw_db_self.GetSqliteDB(),
						Ctx:  context.Background(),
						Lock: fw_db_self.GetSqliteLock(),
					}
					mapperMerchants := web_mapper.MerchantsMapper{
						DB:   fw_db_self.GetSqliteDB(),
						Ctx:  context.Background(),
						Lock: fw_db_self.GetSqliteLock(),
					}
					trusteeLists, _, err := mapperTrutee.List()
					routeLists, _, err := mapperRoute.List()
					if err != nil {
						fw_log.Slogger.Info(err.Error())
						break
					}
					customerLists, _, err := mapperCustomerInfoWms.List("CO")
					if err != nil {
						fw_log.Slogger.Info(err.Error())
						break
					}
					for _, v := range customerLists {
						var curRouteModel web_model.TransRoute
						var curTrusteeModel web_model.TransTrustee
						for _, n := range routeLists {
							if n.Name == v.Route {
								curRouteModel = *n
								break
							}
						}
						for _, s := range trusteeLists {
							if v.Owner == s.Code {
								curTrusteeModel = *s
								break
							}
						}
						var customerModel web_model.TransMerchants
						customerModel.Code = v.CustomerCode
						customerModel.Name = v.ExpressionCn
						if v.ActiveFlag == "Y" {
							customerModel.Status = "1"
						} else {
							customerModel.Status = "2"
						}
						customerModel.Addr = v.Address
						customerModel.Contact = v.Contact
						customerModel.Telephone = v.Telephone
						customerModel.DeliveryAddr = v.DeliveryAddr
						customerModel.ShortCode = v.ShortCode
						customerModel.ShortName = v.ExpressionEn
						if lo.IsNotEmpty(curRouteModel) {
							customerModel.RouteID = curRouteModel.ID
							customerModel.RouteName = curRouteModel.Name
						}
						if lo.IsNotEmpty(curTrusteeModel) {
							customerModel.TrusteeID = curTrusteeModel.ID
							customerModel.TrusteeName = curTrusteeModel.Name
						}
						_, err = mapperMerchants.Upsert(&customerModel)
						if err != nil {
							fw_log.Slogger.Info(err.Error())
						}
					}
					break
					// 同步委托人
				case msg.Cmd == EVENT_CMD_SYNC_TRUSTEE_INFO:
					mapperCustomerInfoWms := web_wms_mapper.CustomerMapper{
						DB:  fw_db_wms.GetSqlserverDB(),
						Ctx: context.Background(),
					}
					mapperTrustee := web_mapper.TrusteeMapper{
						DB:   fw_db_self.GetSqliteDB(),
						Ctx:  context.Background(),
						Lock: fw_db_self.GetSqliteLock(),
					}
					customerLists, _, err := mapperCustomerInfoWms.List("OW")
					if err != nil {
						fw_log.Slogger.Info(err.Error())
						break
					}
					for _, v := range customerLists {
						var customerModel web_model.TransTrustee
						customerModel.Code = v.CustomerCode
						customerModel.Name = v.ExpressionCn
						if v.ActiveFlag == "Y" {
							customerModel.Status = "1"
						} else {
							customerModel.Status = "2"
						}
						customerModel.Addr = v.Address
						customerModel.Contact = v.Contact
						customerModel.Telephone = v.Telephone
						customerModel.DeliveryAddr = v.DeliveryAddr
						customerModel.ShortCode = v.ShortCode
						customerModel.ShortName = v.ExpressionEn
						_, err = mapperTrustee.Upsert(&customerModel)
						if err != nil {
							fw_log.Slogger.Info(err.Error())
						}
					}
					break
				case msg.Cmd == EVENT_CMD_SYNC_ORDER_INFO:
					mapperOrderHeaderWms := web_wms_mapper.OutboundOrderHeaderMapper{
						DB:  fw_db_wms.GetSqlserverDB(),
						Ctx: context.Background(),
					}
					mapperOrderDetailWms := web_wms_mapper.OutboundOrderDetailMapper{
						DB:  fw_db_wms.GetSqlserverDB(),
						Ctx: context.Background(),
					}
					mapperOrder := web_mapper.OrderrMapper{
						DB:   fw_db_self.GetSqliteDB(),
						Ctx:  context.Background(),
						Lock: fw_db_self.GetSqliteLock(),
					}
					mapperOrderDetail := web_mapper.OrderDetailMapper{
						DB:   fw_db_self.GetSqliteDB(),
						Ctx:  context.Background(),
						Lock: fw_db_self.GetSqliteLock(),
					}
					orderHeaderLists, err := mapperOrderHeaderWms.QueryByStatusOk()
					if err != nil {
						fw_log.Slogger.Info(err.Error())
						break
					}
					tmpOrderList := make([]*web_vo.OutboundOrderHeader, 0)
					// 订单更新
					for _, v := range orderHeaderLists {
						var modelOrder web_model.TransOrder
						modelOrder.OrderCode = v.OrderCode
						modelOrder.Route = v.Route
						modelOrder.CustomerName = v.ExpressionCn
						modelOrder.CustomerCode = v.CustomerCode
						modelOrder.PackCount = v.PackCount
						modelOrder.PriorityLevel = v.PriorityLevel
						modelOrder.OrderType = v.OrderType
						modelOrder.Status = "1"
						_, err = mapperOrder.Upsert(&modelOrder)
						if err != nil {
							fw_log.Slogger.Info(err.Error())
						} else {
							tmpOrderList = append(tmpOrderList, v)
						}
					}
					// 明细更新
					index := 0
					for k, _ := range tmpOrderList { // 每300单查询一次，尽量减少查询次数
						if (k+1)%300 == 0 || k == len(tmpOrderList)-1 {
							orderCodes := []string{}
							for _, n := range tmpOrderList[index : k+1] {
								orderCodes = append(orderCodes, n.OrderCode)
							}
							orderDetails, err := mapperOrderDetailWms.QueryByOrderCodes(orderCodes)
							if err != nil {
								fw_log.Slogger.Info(err.Error())
								continue
							}
							for _, j := range orderDetails {
								var modelOrderDetail web_model.TransOrderDetail
								modelOrderDetail.OrderCode = j.OrderCode
								modelOrderDetail.OrderLineNum = j.OrderLineNum
								modelOrderDetail.Count = j.Count
								modelOrderDetail.LotNum = j.LotNum
								modelOrderDetail.ExpireDate = carbon.CreateFromStdTime(j.ExpireDate).ToDateString()
								modelOrderDetail.Formula = j.MedicalType
								modelOrderDetail.StorageType = j.StorageType
								modelOrderDetail.ProductCode = j.ProductCode
								modelOrderDetail.ProductDate = carbon.CreateFromStdTime(j.ProductDate).ToDateString()
								modelOrderDetail.ProductEn = j.ExpressionEn
								modelOrderDetail.ProductName = j.ExpressionCn
								modelOrderDetail.Unit = j.PackageUnit
								modelOrderDetail.Specifications = j.Specifications
								modelOrderDetail.Manufacturer = j.Manufacturer
								modelOrderDetail.ApprovalNum = j.ApprovalNum
								modelOrderDetail.ApprovalValidTime = carbon.CreateFromStdTime(j.RegisterTime).ToDateString()
								modelOrderDetail.PermitHolder = j.PermitHolder
								_, err = mapperOrderDetail.Upsert(&modelOrderDetail)
								if err != nil {
									fw_log.Slogger.Info(err.Error())
								}
							}
							index = k + 1
						}
					}
					// 更新订单温控类型
					err = mapperOrder.UpdateOrderTempType()
					if err != nil {
						fw_log.Slogger.Info(err.Error())
					}
					// 更新订单线路，erp没有维护，在运输系统维护的情况
					err = mapperOrder.UpdateOrderRoute()
					if err != nil {
						fw_log.Slogger.Info(err.Error())
					}
					break
				}
				break
			}
		}
	}()
}
